package com.bbcare.followup.plat.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.bbcare.comm.Constants;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.PostObjectPolicy;

@Service
public class AliyunOSSClient {
	private final Log logger = LogFactory.getLog(AliyunOSSClient.class);
    public AliyunOSSClient() {
    }

    /**
     * 获取Policy签名等信息
     * @param map   过期时间 默认60s过期
     * @return
     */
    public PostObjectPolicy getPostObjectPolicy(Map<String, Object> map) {
    	logger.info("getPostObjectPolicy  : "+map);
    	String type = (String) map.get("type");
    	String tenantId = (String) map.get("tenantId");
    	//项目id
    	String ACCESS_ID =PropertiesUtils.getProperty("ACCESS_ID");
    	//密码
		String ACCESS_KEY = PropertiesUtils.getProperty("ACCESS_KEY");
		//bucket名称
		String bucketName="";
		//文件上传地址
		String key="";
		//阿里地址
		String endpoint="";

		if(StringUtils.isBlank(type)) {
			bucketName=PropertiesUtils.getProperty("bucketName");
			key=PropertiesUtils.getProperty("commonImage");
			endpoint=PropertiesUtils.getProperty("endpoint");
		}else if("1".equals(type)) {
			bucketName=PropertiesUtils.getProperty("bucketNameNew");
			 // 文件上传路径：基础路径+租户id
	        key = ToolUtils.getUploadFilePath(Constants.FILE_UPLOAD_FOR_IMG_BASIC_PATH_ID_NAME, tenantId);
			endpoint=PropertiesUtils.getProperty("endpointNew");
		}
		//计算过期时间
		long time = (int) map.get("time");
        long expireEndTime = System.currentTimeMillis() + time* 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, key);
        //新建客户端
        OSSClient ossClient =  new OSSClient(endpoint, ACCESS_ID, ACCESS_KEY);
        //获得鉴权策略
        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = new byte[0];
        try {
            binaryData = postPolicy.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //进行base64位加密
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        //获得签名
        String postSignature = ossClient.calculatePostSignature(postPolicy);
        PostObjectPolicy policy = new PostObjectPolicy();
        //项目id
        policy.setAccessId(ACCESS_ID);
        //阿里域名
        policy.setHost("http://" + bucketName + "." + endpoint);
        ////存储在oss的文件路径
        policy.setDir(key);
        //过期时间
        policy.setExpire(String.valueOf(expireEndTime / 1000));
        //鉴权策略
        policy.setPolicy(encodedPolicy);
        //签名
        policy.setSignature(postSignature);
        return policy;
    }
}
